<template>
  <div>
    <el-dialog
      title="注：换行用<br>"
      v-model="state.visible"
      width="1200px"
    >
      <div class="dialogContent">    
         
        <el-form :model="state.question" :rules="state.rules" ref="questionRef" label-width="100px" class="questionForm">
          <el-form-item label="内容：" prop="content">
            <div style="width:100%;">
              <TinymceNew id="contentEditor" :value="state.question.content" :modelValue="state.question.content" @update:modelValue="inputContent" ref="contentEditorRef"></TinymceNew>        
            </div>
          </el-form-item>
         <!-- <el-form-item label="题干：" prop="content">         
            <WangEditor id="contentEditor"
              ref="contentEditorRef"
              @getEditorContent="onEditorChange" 
              :initValue="state.question.content"        
            />
         </el-form-item> -->
          <el-form-item label="答案：" prop="answer"> 
            <div style="width:100%;">
              <QuillEditor v-model:content="state.question.answer" @update:content="handleUpdateAnswerQuill" ref="answerEditorRef" /> 
            </div>
          </el-form-item>
          <el-form-item label="解析：" prop="explain">
            <!-- <div style="width:500px;">
             
              <editor :value="state.question.explain_front" @input="inputExplain" ref="explainEditorRef" id="explain_front" />
            </div>
          </el-form-item>
          <el-form-item label="插图：">
            <UploadImage ref="uploadImage_explain" :limit="5" :fileList="state.fileList_explain" :action="state.uploadImgServer" :father_method="getImageList_explain"></UploadImage> -->
            <!-- <WangEditor id="explainEditor"
              ref="explainEditorRef"
              @getEditorContent="onEditorExplainChange"         
              :initValue="state.question.explain"
              />  -->
            <div style="width:100%;">       
              <VueQuillEditor v-model:content='state.question.explain' @update:content="handleUpdateExplainQuill" ref="explainEditorRef" />   
            </div>
            <!-- <el-image v-for="url in state.question.images_explain" :key="url" :src="url" style="width: 300px;" />   -->
            <!-- <el-button :icon="Delete" size="small" @click="onClickClearExplainImages()" ></el-button> -->
          </el-form-item>

          <!-- 设置题型 -->
          <el-form-item label="题型：" prop="type">
              <el-select v-model="state.question.type" class="m-2" placeholder="题型" size="small" @change="typeSelectChange">
                <el-option
                  v-for="item in questionTypeOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="难度：" prop="difficulty_level">            
              <el-select v-model="state.question.difficulty_level" class="m-2" placeholder="难度：" size="small">
                <el-option
                  v-for="item in difficultyLevelOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="库币：" prop="bank_point">
              <el-input-number v-model="state.question.bank_point"></el-input-number>
            </el-form-item>           
         
            <el-form-item label="已选知识点：" prop="knowledgepoint">
              <el-button type="primary" v-for="(item, index) in state.question.knowledgepoint" :key="index" @click="onClickKnowledgeItem(index)">
                {{ item.name }}
              </el-button>
              <div class="knowledgepoint">
                <el-dropdown @command="handleCommand" size="large">
                    <span class="el-dropdown-link">
                        关联知识点
                        <el-icon class="el-icon--right">
                          <arrow-down />
                        </el-icon>
                    </span>
                    <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="1">信息技术</el-dropdown-item>
                        <el-dropdown-item command="2">通用技术</el-dropdown-item>
                        <el-dropdown-item command="3">职高计算机</el-dropdown-item>
                    </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <div class="knowledgepointList" v-show="showKnowledgepointList">
                  <el-button
                    v-for="item in state.knowledgepointList"
                    :key="item.name"
                    :type="getButtonType(item.id)"
                    text
                    size="small"
                    @click="linkKnowledgeClick(item.id,item.name)"
                    >{{ item.name }}
                  </el-button>
                  <el-button
                    text
                    size="small"
                    @click="hideKnowledgepointList"
                  >关闭知识点</el-button>
                </div>
              </div>    
            </el-form-item>
          <el-form-item>
            <el-button type="success" @click="submitUpdateClick()" v-if="isUpdate()">更新</el-button>
            <el-button type="success" @click="submitEdit()" v-if="props.type=='edit'">保存</el-button>
            <el-button type="warning" @click="resetForm()">取消</el-button>
            <el-button type="success" @click="submitEditAndPublish()"  v-if="isModify()">保存并发布</el-button>
          </el-form-item>
        </el-form>
        <div class="jiaodui">
          <h1>最终效果</h1>
            <div>【题】</div>
            <div v-html="state.question.content" class="line-break"></div>           
            <!-- <el-image v-for="url in state.question.images" :key="url" :src="url" style="width: 200px;height: 160px;" />  -->
            <div>【答案】</div>
            <div v-html="state.question.answer" class="line-break"></div>
            <!-- <el-image v-for="url in state.question.images_answer" :key="url" :src="url" style="width: 200px;height: 160px;" /> -->
            <div>【解析】</div>
            <div v-html="state.question.explain" class="line-break"></div>
            <!-- <el-image v-for="url in state.question.images_explain" :key="url" :src="url" style="width: 200px;height: 160px;" />      -->
            <p>【题型】{{ state.question.type_cn }}</p>
            <!-- <span>【难度】</span>
            <el-rate v-model="state.question.difficulty_level" disabled/> -->
            <p>库币：{{ state.question.bank_point }}</p>
            
        </div>
    </div>
      <template #footer>
        <div class="dialog-footer">          
          <el-button type="primary" @click="state.visible = false">关 闭</el-button>          
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>

  import { reactive, ref, toRefs, onMounted, watch, onBeforeMount, computed } from 'vue'
  import { localGet, uploadImgServer, convertQuestionFormat, deleteQuestionItem,deepClone } from '@/utils'
  import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
  import { ElMessage, progressProps } from 'element-plus'
  import axios from '@/utils/axios'
  // import UploadImage from '@/components/UploadImage.vue';
  // import TinymceEditor from "@/components/tinymce.vue"
  // import TinymceEditorExpalin from "@/components/tinymce.vue"
  import TinymceNew from "@/components/TinymceNew.vue"
  import QuillEditor from '@/components/QuillEditor.vue';
  // import WangEditor from '@/components/WangEditor.vue'
  import VueQuillEditor from '@/components/VueQuillEditor/index.vue' 

  const showKnowledgepointList = ref(false)   //显示和隐藏知识点
  const contentEditorRef=ref(null)      // 题干富文本编辑器 ref
  const answerEditorRef=ref(null)       // 答案富文本编辑器 ref
  const explainEditorRef = ref(null)    // 解析富文本编辑器 ref
  const questionRef = ref(null)
  const state = reactive({
    visible: false,     //控制本组件的对话框显示和隐藏
    rules: { // 规则
      content: [
        {required: 'true', message: '请填写题目内容', trigger: ['change']}
      ],      
      answer: [
        { required: 'true', message: '请填写参考答案', trigger: ['change'] }
      ],
      explain: [
        { required: 'true', message: '请填写解析', trigger: ['change'] }
      ],
      bank_point: [
        { required: 'true', message: '请填写库币', trigger: ['change'] },
        {type:"number" ,min: 1, max: 100, message: '大小要在1到100', trigger: 'blur' }
      ],
    },
    token: localGet('token') || '', // 存在本地的 token
    uploadImgServer,
    question: Object,
    father_id: Number,
    fileList:[],
    fileList_explain:[],
    fileList_answer:[],
    knowledgepointList:[],
    subjectId:'1',
  });
  const props = defineProps({
    type:String,
    father_method:Function,
    question:Object,
  })
  const buttonTypeList = ['primary', 'success', 'info', 'warning', 'danger']
  const getButtonType =(value)=>{
    return buttonTypeList[value % buttonTypeList.length]
  }
  // 点击知识点删除
  const onClickKnowledgeItem = (index)=>{
    state.question.knowledgepoint.splice(index,1)
  }
 // 隐藏知识点列表
 const hideKnowledgepointList = () => {
    showKnowledgepointList.value = false
  }
// 把知识点关联到题目
const linkKnowledgeClick=(knowledgeId,knowledgeName)=>{
  let knowledge_data = {name: knowledgeName, id: knowledgeId}
  state.question.knowledgepoint.push(knowledge_data)
}
// 获取学科的知识点
const getKnowledgepointBySubject=()=>{
  if(state.subjectId<1){
    ElMessage.error('先选择学科，再获取');
    return false;
  }
  let params={
    pk:state.subjectId,
  }
  console.log("我要获取知识点了：",state.subjectId)
  axios.get('/GetKnowledgepointBySubjectApiView/',{params}).then(res => {
    console.log("获取知识点结果：",res)
    if (res.code==200){
      ElMessage.success('恭喜，获取知识点成功')
      state.knowledgepointList = deepClone(res.data.results)
      return true
    }else
    if(res.code==1099){
      ElMessage.error('参数错误，获取失败')
      return false
    }else{
      ElMessage.error('服务器错误')
    } 
  })
  .catch((error)=>{
    console.log("error:", error)
  })   
}
// 选中学科获取知识点
const handleCommand=(command=1)=>{
    command = parseInt(command)
    state.subjectId = command
    // console.log("下拉设置学科",state.subjectId)
    getKnowledgepointBySubject()
    showKnowledgepointList.value = true
}
  // wangEditor子组件发过来的更新内容
  const onEditorExplainChange=(val1,val2)=>{
    state.question.explain = val2
  }
  // 初始化题目
  const initQuestion=computed(()=>{
    return deepClone(props.question)
  })
  watch(initQuestion,(newVal)=>{
    console.log("监视着props.question",newVal)
  })
  // 更新从子组件vueQuillEditor发过来的更新解析
  const handleUpdateExplainQuill = (val) => {
    console.log('子组件发来解析：',val)
    state.question.explain = val
  }
  // 更新从子组件vueQuillEditor发过来的内容更新答案
  const handleUpdateAnswerQuill = (val) => {
    console.log('子组件发来答案：',val)
    state.question.answer = val
  }
  onMounted(() => {    

  })
  const questionTypeOption = [
    {
      value : 1,
      label : '选择题',
    },
    {
      value : 2,
      label : '填空题',
    },
  ]
  const difficultyLevelOption = [
    {
      value : 1,
      label : '入门',
    },
    {
      value : 2,
      label : '中级',
    },
    {
      value : 3,
      label : '较难',
    },
    {
      value : 4,
      label : '高级',
    },
    {
      value : 5,
      label : '压轴',
    },
  ]
  const openLevelOption = [
    {
      value : 'public',
      label : '所有人可见',
    },
    {
      value : 'private',
      label : '仅自己可见',
    },
    // {
    //   value : 'friend',
    //   label : '好友可见',
    // },
  ]
 
  var reg2 = /<p>/g
  var reg3 = /<\/p>/g
  // 题目内容富文本框tinyeditor输入
  const inputContent=(val)=> {
    state.question.content=val
    console.log("富文本输入内容",state.question.content)
  }
  // 题目内容富文本框tinyeditor输入
   const inputAnswer=(val)=> {
    state.question.answer=val
    console.log("富文本输入答案：",state.question.answer)
  }
  // tinyeditor富文本框输入解析内容
  const inputExplain=(val)=> {
    state.question.explain=val   
  }

  const typeSelectChange=(value)=>{
    // console.log("选择题型改变了", value)
    state.question.type=value
    state.question.type_cn=questionTypeOption[value-1].label
  }
  // 保存修改,并把修改后的题目返还给父组件，类型为edit
  const submitEdit=()=>{
      questionRef.value.validate((vaild, obj) => {
        if (vaild) {
          console.log("表单验证成功，我要发消息给父组件：")
          props.father_method(state.father_id, state.question)
          state.visible = false
        }else{
          ElMessage("表单没有完成！")
          console.log("表单没有通过！",obj)       
          for (let key in obj) {
            console.log("具体原因：", obj[key][0].message)
            return false;
          }
        }
      })
    }
 
  //保存修改，并发布题目(该方法未启用),被以下submitUpdateClick替代
  const submitEditAndPublish =()=>{
    if(props.type === "modifySelectedQuestion"){
      questionRef.value.validate((vaild, obj) => {
        if (vaild) {
          console.log("表单验证成功，我要发消息给父组件：")
          //执行父组件的方法，将当前题目的修改状态保存到父组件中
          props.father_method(state.father_id, state.question)
          // 持久化到数据库中,并把<br>符号转换回\n，发给后端         
          let params = {           
            answer: state.question.answer,
            explain: state.question.explain,
            content: state.question.content,
            pictures: state.question.pictures,
            reference: state.question.reference,
            type: state.question.type,
            difficulty_level: state.question.difficulty_level,
            knowledgepoint: state.question.knowledgepoint,
            open_level: 'private',
            pictures_answer: state.pictures_answer,
            pictures_explain: state.pictures_explain
          }     
          axios.post(`/questions/`,params).then(res =>{
            if (res.code == 200){
              ElMessage("恭喜你，题目发布成功，在我的创作栏目查看！")
            }else{
              ElMessage("很遗憾，题目发布失败！")
              console.log("题目发布失败：", data.message)
            }
          }) 
          state.visible = false
        }else{
          ElMessage("表单没有完成！")
          console.log("表单没有通过！",obj)       
          for (let key in obj) {
            console.log("具体原因：", obj[key][0].message)
            return false;
          }
        }
      })
    }
  }
  // 显示本对话框
  const open = (father_id, question) => {
    state.visible = true
    console.log("父组件传过来了：",father_id,deepClone(question))
    state.question = question
    state.father_id = father_id 
    // state.fileList = convertImage(state.question.images)
    // state.fileList_explain = convertImage(state.question.images_explain)
  };
  // 关闭弹窗
  const close = () => {
    state.visible = false
  };
 
  // 取消按钮
  const resetForm=()=>{
    state.visible = false
  }
  // 是否更新操作
  const isUpdate=()=>{
    return props.type == 'update'
  }
  // 是否为修改操作
    const isModify=()=>{
    return props.type == 'modifySelectedQuestion'
  }
  // 更新题目到数据库按钮处理
  const submitUpdateClick=()=>{
    // console.log("修改后的题目：",state.question) 
    // state.question = convertQuestionFormat(state.question)
    // console.log("发给后端前的题目：",state.question)
    questionRef.value.validate((vaild, obj) => {
      if (vaild) {
        let params = {
          id: state.question.id,                
          content: state.question.content,
          // pictures: state.question.pictures,
          answer: state.question.answer,
          explain: state.question.explain,
          // pictures_answer: state.question.pictures_answer,
          // pictures_explain: state.question.pictures_explain,
          // reference: state.question.reference,
          type: state.question.type,
          // difficulty_level: state.question.difficulty_level,
          knowledgepoint: state.question.knowledgepoint,
          open_level: state.question.open_level,
          // top: state.question.top,
          bank_point: state.question.bank_point
        }
        axios.put(`/questions/${state.question.id}/`, params).then((result) => {
          if(result.code==200){
            ElMessage.success( '操作成功！')
            state.visible = false
            // 执行父组件的回调函数
            if(props.father_method)props.father_method()    
          }else{
            console.log("提交错误", result)
          }       
        }).catch((error)=>{
          console.log("更新题目错误：", error)
        })
      }else{                //输出表单没有通过的原因
        console.log("表单没有通过！",obj)
        for (let key in obj) {
          console.log("具体错误：",obj[key][0].message)          
        }
      }
    })
  }
  // 将需要暴露出去的数据与方法都可以暴露出去
  defineExpose({ open, close })
</script>

<style scoped>
  .jiaodui{
    width:450px;
    border-width: 1px;
    border-color: black;
    border-style: solid;
  }

  .dialogContent{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: flex-start;
  }
  .questionForm{
    width: 700px;
    border-width: 1px;
    border-color: black;
    border-style: solid;    
  }
  .dialog-footer{
    display: flex;
    justify-content: center;
  } 
  .line-break{
    white-space: pre-wrap;
  }
  .inlineImage{
    display: inline;
    width:  150px;
    height: 100px;
  }
 
</style>